package cn.ainit.sys.socket;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.ainit.sys.common.dao.SysBaseDao;

@Transactional
@Repository
public class MsgDaoImpl extends SysBaseDao implements MsgDao{
	@Override
	/****  Map<用户ID，List<Map<信息ID，信息 >>>    ***/
	public Map<String, List<Map<String, String>>> loadMsg() throws Exception {
		Map<String, List<Map<String, String>>> umsgMap = new HashMap<String, List<Map<String, String>>>();
		try {
			String sql = "select * from sys_task_msg where M_TS IS NULL OR M_TS != 'T' and o_id in (select s.userid from sys_session_contorl s)";
			List<Map<String, Object>> msgList = this.getJdbcTemplate().queryForList(sql);
			
			for(int i = 0; i < msgList.size(); i ++){
				if (umsgMap.containsKey(msgList.get(i).get("O_ID").toString().trim())) {
					Map<String, String> idmsgMap = new HashMap<String, String>();
					idmsgMap.put(msgList.get(i).get("M_ID").toString(), msgList.get(i).get("M_MSG").toString());
					umsgMap.get((String) msgList.get(i).get("O_ID")).add(idmsgMap);
				}else {
					umsgMap.put(msgList.get(i).get("O_ID").toString().trim(), new ArrayList());
					Map<String, String> idmsgMap = new HashMap<String, String>();
					idmsgMap.put(msgList.get(i).get("M_ID").toString(), msgList.get(i).get("M_MSG").toString());
					umsgMap.get((String) msgList.get(i).get("O_ID")).add(idmsgMap);
				}
			}
		} catch (Exception e) {
			System.out.print(e.getMessage());
		}
		return umsgMap;
	}
	
	
	
	
	
	@Override
	public List<Map<String, Object>> loadMsgListDao() {
		String sql = "select * from sys_task_msg where M_TS IS NULL OR M_TS != 'T' and o_id in (select s.userid from sys_session_contorl s)";
		List<Map<String, Object>> msgList = this.getJdbcTemplate().queryForList(sql);
		return msgList;
	}
	
	@Override
	public void upTs(List<String> msgids) throws Exception {
		StringBuffer ids = new StringBuffer();
		ids.append("(");
		for (int i = 0; i < msgids.size(); i++) {
			ids.append("'"+msgids.get(i)+"'");
			if (i < msgids.size()-1) {
				ids.append(",");
			}
		}
		ids.append(")");
		String upTs = " update sys_task_msg set M_TS = 'T' where M_ID in "+ids.toString();
		Connection conn  = null;
		PreparedStatement pStatement = null;
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			pStatement = conn.prepareStatement(upTs);
			pStatement.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (conn != null) {
				conn.close();
			}
			if (pStatement != null) 
			{
				pStatement.close();
			}
		}
	}
}



